package com.hhl.member.service.impl;

import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.hhl.base.BaseApiService;
import com.hhl.base.BaseRedisService;
import com.hhl.base.ResponseBase;
import com.hhl.constants.Constants;
import com.hhl.member.entity.User;
import com.hhl.member.feign.WechatAppServiceFeign;
import com.hhl.member.mq.RegisterMailboxProducer;
import com.hhl.member.service.MemberService;
import com.hhl.member.service.dao.MemberDao;
import com.hhl.utils.MD5Util;
import com.hhl.utils.TokenUtils;
import com.hhl.wechat.entity.AppEntity;

import lombok.extern.slf4j.Slf4j;

/**
 * 说明:会员服务接口实现<br/>
 * 创建时间：2019年3月30日 下午3:13:10<br/>
 * @author hhl
 */
@RestController
@Slf4j
public class MemberServiceImpl extends BaseApiService implements MemberService {
	@Autowired
	WechatAppServiceFeign wechatAppServiceFeign;
	@Autowired
	MemberDao memberDao;
	@Autowired
	private RegisterMailboxProducer registerMailboxProducer;
	@Value("${messages.queue}")
	private String MESSAGESQUEUE;
	@Autowired
	BaseRedisService baseRedisService;

	/**
	 * 会员服务调用微信服务
	 */
	@Override
	public AppEntity memberInvokeWechat() {
		return wechatAppServiceFeign.getApp();
	}

	@Override
	public ResponseBase setRedisTest(String key, String value) {
		return null;
	}

	@Override
	public ResponseBase getRedis(String key) {
		return null;
	}

	public ResponseBase getUserById(String id) {
		User user = memberDao.findByID("37");
		if (user == null) {
			return setResultError("未找到用户信息");
		}
		return setResultSuccess(user);
	}

	@Override
	public ResponseBase registerUser(@RequestBody User user) {
//		User u = new User();
//		u.setUsername("hhlhhl");
//		u.setPassword("hhlhhl");
//		u.setEmail("1414454875@qq.com");

		Integer i =memberDao.insertUser(user);
		if (i < 1) {
			return setResultError("注册失败");
		}
		
		// 采用异步方式发送消息
		String email = user.getEmail();
		String json = emailJson(email);
		log.info("####会员服务推送消息到消息服务平台####json:{}", json);
		sendMsg(json);
		
		return setResultSuccess("注册成功");
	}

	private String emailJson(String email) {
		JSONObject rootJson = new JSONObject();
		JSONObject header = new JSONObject();
		header.put("interfaceType", Constants.MSG_EMAIL);
		JSONObject content = new JSONObject();
		content.put("email", email);
		rootJson.put("header", header);
		rootJson.put("content", content);
		return rootJson.toJSONString();
	}
	
	private void sendMsg(String json) {
		ActiveMQQueue activeMQQueue = new ActiveMQQueue(MESSAGESQUEUE);
		registerMailboxProducer.sendMsg(activeMQQueue, json);
	}

	@Override
	public ResponseBase login(@RequestBody User user) {
		/**
		 * 1.验证参数
		 * 2.数据库查找账号密码是否正确
		 * 3.如果账号密码正确，对应生成token
		 * 4.存放在redis中，key为token value 为userid
		 * 5.直接返回token
		 */
		if(StringUtils.isEmpty(user.getUsername())||StringUtils.isEmpty(user.getPassword())){
			return setResultError("参数不齐");
		}
		
		String pwd = MD5Util.MD5(user.getPassword());
		User user1 = memberDao.login(user.getUsername(), pwd);
		if(user1==null) {
			return setResultError("账号密码错误");
		}
		
		String token = TokenUtils.getMemberToken();
		Integer id = user1.getId();
		baseRedisService.setString(token,id+"", Constants.TOKEN_MEMBER_TIME);
		
		JSONObject json = new JSONObject();
		json.put("token", token);
		return setResultSuccess(json);
	}

	@Override
	public ResponseBase findByTokenUser(String token) {
		// 1.验证参数
		if (StringUtils.isEmpty(token)) {
			return setResultError("token不能为空!");
		}
		// 2.从redis中 使用token 查找对应 userid
		String strUserId = (String) baseRedisService.getString(token);
		if (StringUtils.isEmpty(strUserId)) {
			return setResultError("token无效或者已经过期!");
		}
		// 3.使用userid数据库查询用户信息返回给客户端
		Long userId = Long.parseLong(strUserId);
		User user = memberDao.findByID(userId+"");
		if (user == null) {
			return setResultError("为查找到该用户信息");
		}
		user.setPassword(null);
		return setResultSuccess(user);
	}

}
